package top.honlnk.czuan.common.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.honlnk.czuan.common.exception.CustomException;
import top.honlnk.czuan.pojo.entity.User;
import top.honlnk.czuan.service.UserService;

import java.util.Date;

@SuppressWarnings("ALL")

@Slf4j
public class JWTTokenUtil {
    private static UserService staticUserService;

    @Resource
    private UserService userService;

    @PostConstruct
    public void serUserService() {
        staticUserService = userService;
    }

    /**
     * 生成token
     */
    public static String genToken(User user, int days) {
        DateTime dateTime;
        if (days == 0) {
            dateTime = DateUtil.offsetHour(new Date(), 6);
        } else {
            dateTime = DateUtil.offsetDay(new Date(), days);
        }
        Integer powerValue = user.getPower();
        // 后续加入在powerValue中加解析权限，然后加入到token中
        return JWT.create().withAudience(user.getId().toString()) // 将 user id 保存到 token 里面，作为载荷
                .withExpiresAt(dateTime)  // 6小时后过期
                .withClaim("powerValue", powerValue)  // 加入添加权限
                .sign(Algorithm.HMAC256(user.getPassword())); // 以 password 作为 token 的密钥
    }


    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser() {
        String token;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");

            if (StrUtil.isBlank(token)) {
                token = request.getParameter("token");
            }

            if (StrUtil.isBlank(token)) {
                log.error("获取当前登录用户信息失败：{}", token);
                throw new CustomException("您还未登录，请重新登录");
            }

            // 解析 token，获取用户信息
            var decodedToken = JWT.decode(token);
            String userId = decodedToken.getAudience().get(0);
            Integer powerValue = decodedToken.getClaim("powerValue").asInt();

//            // 构建用户对象
            return User.builder()
                    .id(Integer.valueOf(userId))
                    .power(powerValue)
                    .build();

        } catch (Exception e) {
            log.error("获取当前登录用户信息失败", e);
            return null;
        }
    }
}